<!--
 * @Author: June
 * @Date: 2022-11-19 01:47:30
 * @LastEditors: June
 * @LastEditTime: 2022-11-21 16:05:31
 * @Description:
 *
-->
<template>
  <el-upload ref="upload" class="upload-demo" action :auto-upload="true" :show-file-list="false" :http-request="uploadFile" :before-upload="beforeUpload">
    <el-button v-if="titleFont" type="primary" icon="el-icon-upload2">数据导出</el-button>
    <el-button v-else type="primary" icon="el-icon-upload2">Excel导出</el-button>
  </el-upload>
</template>
<script>
export default {
  props: {
    url: {
      type: String,
      default: () => {
        return ''
      }
    },
    titleFont: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  methods: {
    /** 上传文件之前校验 */
    beforeUpload(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (extension !== 'xlsx' && extension !== 'xls') {
        this.$message.warning('只能上传后缀是.xlsx、.xls的文件！') // 只能上传后缀是.xlsx的文件！
      }
      return !(extension !== 'xlsx' && extension !== 'xls')
    },
    /** 导入文件 */
    uploadFile(file) {
      const loading = this.$loading({
        lock: true,
        text: '数据导入中...', // 数据导入中...
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const form = new FormData()
      form.append('file', file.file)
      this.$axios.post(this.url, form).then((res) => {
        try {
          if (res?.data.code === 200) {
            if (
              res.data.data.length < 1 ||
              JSON.stringify(res.data.data) === '{}'
            ) {
              this.$message.success('导入成功') // 导入成功
              this.$emit('getTableInfo')
              loading.close()
            } else {
              this.$alert(res.data.data.toString(), '提示', {
                confirmButtonText: '确认',
                type: 'error',
                callback: (action) => {
                  loading.close()
                }
              })
            }
          } else {
            loading.close()
          }
        } catch (error) {
          loading.close()
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>
.upload-demo {
  display: inline-block;
  padding: 0 10px;
  .el-upload {
    width: 100% !important;
    height: 100% !important;
    display: block !important;
  }
}
</style>
<style lang='scss'>
</style>
